<template>
    <el-card style="max-width: 800px">
        <template #header>
            
            <div class="card-header">
                <span>新增盘点</span>
            </div>
        </template>
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px">
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="盘点单号" prop="inventoryCode">
                        <el-input v-model="ruleForm.inventoryCode" placeholder="请输入盘点单号" disabled />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="盘点结果" prop="resultId">
                        <el-select v-model="ruleForm.resultId" placeholder="请选择盘点结果" style="width: 100%">
                            <el-option v-for="a in Result" :key="a.resultId" :label="a.resultName"
                                :value="a.resultId" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="仓库" prop="depotId">
                        <el-select v-model="ruleForm.depotId" placeholder="请选择仓库" style="width: 100%">
                            <el-option v-for="a in Depot" :key="a.depotId" :label="a.depotName" :value="a.depotId" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="盘点类型" prop="iTypeId">
                        <el-select v-model="ruleForm.iTypeId" placeholder="请选择盘点类型" style="width: 100%">
                            <el-option v-for="a in IType" :key="a.iTypeId" :label="a.iTypeName" :value="a.iTypeId" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="盘点开始时间" prop="iStartTime">
                        <el-date-picker v-model="ruleForm.iStartTime" type="datetime" placeholder="选择开始时间"
                            style="width: 100%" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="盘点结束时间" prop="iEndTime">
                        <el-date-picker v-model="ruleForm.iEndTime" type="datetime" placeholder="选择结束时间"
                            style="width: 100%" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="出库状态" prop="dispatchState">
                        <el-select v-model="ruleForm.dispatchState" placeholder="请选择出库状态" style="width: 100%">
                            <el-option label="未出库" value="0" />
                            <el-option label="部分出库" value="1" />
                            <el-option label="已出库" value="2" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="入库状态" prop="receiveState">
                        <el-select v-model="ruleForm.receiveState" placeholder="请选择入库状态" style="width: 100%">
                            <el-option label="未入库" value="0" />
                            <el-option label="部分入库" value="1" />
                            <el-option label="已入库" value="2" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="盘点总数量" prop="inventoryNumber">
                        <el-input v-model="ruleForm.inventoryNumber" placeholder="请输入盘点总数量"  />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="盘盈数量" prop="profitLossNumber">
                        <el-input v-model="ruleForm.profitLossNumber" placeholder="请输入盘盈数量"  />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-form-item label="备注" prop="inventoryRemark">
                    <el-input v-model="ruleForm.inventoryRemark" type="textarea" :rows="3" placeholder="请输入备注信息" />
                </el-form-item>
                <el-col :span="12">
                    <el-form-item label="经办人" prop="inventoryHandler">
                        <el-input v-model="ruleForm.inventoryHandler" placeholder="请输入经办人" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    提交
                </el-button>
                <el-button @click="resetForm(ruleFormRef)">重置</el-button>
                <el-button @click="goBack">返回</el-button>
            </el-form-item>
        </el-form>
    </el-card>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import axios from 'axios';
import { http } from '@/axios/axiosHelpers';

const router = useRouter();
onMounted(() => {
    ruleForm.value.inventoryCode = generateInventoryCode();
    getDepot();
    getResult();
    getIType();
})

function generateInventoryCode() {
    // 例如：PDDH + 年月日时分秒 + 3位随机数
    const now = new Date();
    const pad = (n: number) => n.toString().padStart(2, '0');
    const dateStr = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
    const rand = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
    return `PDDH${dateStr}${rand}`;
}
const ruleFormRef = ref<FormInstance>()
const ruleForm = ref({
  inventoryCode: "",
  resultId: null,         // 盘点结果ID
  iTypeId: null,          // 盘点类型ID
  iStartTime: "",         // 盘点开始时间
  iEndTime: "",           // 盘点结束时间
  depotId: null,          // 仓库ID
  dispatchState: null,    // 出库状态
  receiveState: null,     // 入库状态
  inventoryNumber: 0,     // 盘点总数量
  profitLossNumber: 0,    // 盘盈数量
  inventoryHandler: "",   // 经办人
  inventoryRemark: ""     // 备注
})

const locationOptions = ['Home', 'Company', 'School']

const rules = reactive<FormRules>({
    inventoryCode: [
        { required: true, message: '请输入盘点单号', trigger: 'blur' },
    ],
    resultId: [
        {
            required: true,
            message: '请选择盘点结果',
            trigger: 'change',
        },
    ],
    iTypeId: [
        {
            required: true,
            message: '请选择盘点类型',
            trigger: 'change',
        },
    ],
    depotId: [
        {
            required: true,
            message: '请选择仓库',
            trigger: 'change',
        },
    ],
    inventoryNumber: [
        { required: true, message: '请输入盘点总数量', trigger: 'blur' },
    ],
    profitLossNumber: [
        { required: true, message: '请输入盘盈数量', trigger: 'blur' },
    ],
    inventoryRemark: [
        { required: true, message: '请输入备注信息', trigger: 'blur' },
    ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('submit!')
            http.post("/basicwrite/api/Inventory/AddInventory", ruleForm.value).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success(res.data.msg)
                    router.push("/Inventory");
                }
                else {
                    ElMessage.error(res.data.msg)
                }
            });
        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
}))

const goBack = () => {
    router.push("/Inventory");
}
//仓库
const Depot = ref([{
    "depotId": '',
    "depotName": "",
}])
const getDepot = () => {

    console.log(Depot.value);
    http.get("/basicread/api/Depot/GetDepot").then(res => {
        Depot.value = res.data.data
    })
}
//盘点结果
const Result = ref([{
    "resultId": '',
    "resultName": ""
}])
const getResult = () => {

    console.log(Result.value);
    http.get("/basicread/api/Result/GetResult").then(res => {
        Result.value = res.data.data
    })
}

//盘点类型
const IType = ref([{
    "iTypeId": '',
    "iTypeName": ""
}])
const getIType = () => {

    console.log(IType.value);
    http.get("/basicread/api/Result/GetIType").then(res => {
        IType.value = res.data.data
    })
}
</script>

<style scoped>
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.el-form-item {
    margin-bottom: 20px;
}
</style>